<template>
  <!-- 检验规则维护（按类别） -->
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="类别编码">
              <p-input placeholder="类别编码" v-model="queryParam.productTypeCode"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="类别名称">
              <p-input placeholder="类别名称" v-model="queryParam.productType"></p-input>
            </p-form-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="检验类型">
              <j-dict-select-tag
                      placeholder="请选择检验类型"
                      v-model="queryParam.inspectType"
                      dictCode="inspect_type"
              />
            </p-form-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button
                      type="primary"
                      @click="searchReset"
                      icon="reload"
                      style="margin-left: 8px"
              >重置</p-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                 {{ toggleSearchStatus ? '收起' : '展开' }}
                 <p-icon :type="toggleSearchStatus ? 'up' : 'down'" />
               </a>-->
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="openAddBtn" type="primary" icon="plus">新增</p-button>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
        <p-button
                v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
                :key=" 'cgbtn'+index "
                @click="cgButtonJsHandler(item.buttonCode)"
                type="primary"
                :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
        <p-button
                v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
                :key=" 'cgbtn'+index "
                @click="cgButtonActionHandler(item.buttonCode)"
                type="primary"
                :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
      </template>

      <!-- 高级查询区域 -->
      <j-super-query
              :fieldList="fieldList"
              ref="superQueryModal"
              @handleSuperQuery="handleSuperQuery"
      ></j-super-query>

      <p-dropdown v-for="(item,index) in groupTag" :key="index">
        <p-button>
          {{item.name}}
          <p-icon type="down" />
        </p-button>
        <p-menu slot="overlay">
          <template v-for="(items,indexs) in item.data">
            <p-menu-item
                    v-if=" items.optType=='js' "
                    :key="indexs"
                    @click="cgButtonJsHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{items.buttonName}}
            </p-menu-item>
            <p-menu-item
                    v-else-if=" items.optType=='action' "
                    :key="indexs"
                    @click="cgButtonActionHandler(items.buttonCode)"
            >
              <p-icon :type="items.buttonIcon" />
              {{items.buttonName}}
            </p-menu-item>
          </template>
        </p-menu>
      </p-dropdown>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel">
            <p-icon type="delete" />删除
          </p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px">
          批量操作
          <p-icon type="down" />
        </p-button>
      </p-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float:right;">
          <a @click="handleExportXls('检验规则维护（类别）')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
                  name="file"
                  :showUploadList="false"
                  :multiple="false"
                  :headers="tokenHeader"
                  :action="importExcelUrl"
                  @change="handleImportExcel"
          >
            <a>
              <p-icon type="import" />导入
            </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="loadData()">
            <p-icon type="sync" />刷新
          </a>
          <p-divider type="vertical" />
          <p-popover title="自定义列" trigger="click" placement="leftBottom" :overlay-style="getWidth">
            <template slot="content">
              <p-checkbox-group
                      @change="onColSettingsChange"
                      v-model="settingColumns"
                      :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a>
              <p-icon type="setting" />自定义列
            </a>
          </p-popover>
        </span>
      </div>

      <p-table
              ref="table"
              size="middle"
              bordered
              rowKey="id"
              :columns="columns"
              :dataSource="dataSource"
              :scroll="tableScroll"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{fixed:true,selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
              :customRow="clickThenSelect"
              :rowClassName="setRowClassName"
              @change="handleTableChange"
      >
        <!-- 状态插槽 -->
        <template slot="status_dictText" slot-scope="text,record">
          <div v-if="!text" >/</div>
          <p-tag v-else-if="text=='生效'" color="green"><p-icon type="check-circle" />生效</p-tag>
          <p-tag v-else-if="text=='失效'" color="red"><p-icon type="close-circle" />失效</p-tag>

          <!-- <div v-if="text=='生效'" style="color: #00FF00;">{{text}}</div>
           <div v-else style="color: red;">{{text}}</div>-->
        </template>

        <template slot="tightCoefficient" slot-scope="text,record">
          <div v-if="record.inspectAttribute==1">{{record.tightCoefficient}}</div>
        </template>



        <template slot="inspectType_dictText" slot-scope="text,record">
          <div >{{text}}</div>
        </template>

        <div
                slot="filterDropdown"
                slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                style="padding: 8px"
        >
          <p-input
                  v-ant-ref="c => (searchInput = c)"
                  :placeholder="`请输入 ${column.title}`"
                  :value="selectedKeys[0]"
                  style="width: 188px; margin-bottom: 8px; display: block;"
                  @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          />
          <p-button
                  type="primary"
                  icon="search"
                  size="small"
                  style="width: 90px; margin-right: 8px"
                  @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >确认</p-button>
          <p-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">取消</p-button>
        </div>
        <div
                slot="filterDropdownDate"
                slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                style="padding: 8px"
        >
          <p-form-item :label="` ${column.title}`">
            <j-date
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择开始时间"
                    class="query-group-cust"
                    v-model="queryParam[`${column.dataIndex}_begin`]"
            ></j-date>
            <span class="query-group-split-cust"></span>
            <j-date
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择结束时间"
                    class="query-group-cust"
                    v-model="queryParam[`${column.dataIndex}_end`]"
            ></j-date>
          </p-form-item>
          <p-button
                  type="primary"
                  icon="search"
                  size="small"
                  style="width: 90px; margin-right: 8px"
                  @click="() => handleSearchDate(selectedKeys, confirm, column.dataIndex)"
          >确认</p-button>
          <p-button
                  size="small"
                  style="width: 90px"
                  @click="() => handleResetDate(clearFilters,`${column.dataIndex}_begin`,`${column.dataIndex}_end`)"
          >取消</p-button>
        </div>
        <p-icon
                slot="filterIcon"
                slot-scope="filtered"
                type="search"
                :style="{ color: filtered ? '#108ee9' : undefined }"
        />

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
                  v-else
                  :src="getImgView(text)"
                  height="25px"
                  alt="图片不存在"
                  style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
          <p-button
                  v-else
                  :ghost="true"
                  type="primary"
                  icon="download"
                  size="small"
                  @click="uploadFile(text)"
          >下载</p-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="openEditBtn(record)">编辑</a>

          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => deleteBtn(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                      v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                      v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                          href="javascript:void(0);"
                          @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
      </p-table>
    </div>
    <!-- table区域-end -->

    <mesQcInspectRuleBytype-modal ref="modalForm" :EnhanceJS="EnhanceJS" @ok="modalFormOk"></mesQcInspectRuleBytype-modal>





    <p-modal v-model="pModalVisible" :title="pTitle" :width="900" @ok="pModalOk">
      <p-form-model
              ref="ruleForm"
              :model="form"
              :rules="rules"
              :label-col="labelCol" :wrapper-col="wrapperCol"
      >

        <p-divider orientation="left">
          基础信息
        </p-divider>

        <p-row :gutter="24"  >

          <p-col :span="12" >
            <p-form-model-item label="类别编码" prop="productTypeId">
              <p-select v-model="form.productTypeId" placeholder="请选择物料类别" showSearch @change="productTypeIdSelectChange" >
                <p-select-option
                        v-for="(item,index) in productionTypeList"
                        :key="index"
                        :value="item.id+'-'+item.mtypeno"
                >{{item.mtypeno}}</p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col :span="12" >
            <p-form-model-item label="类别名称" prop="productTypeId2">


              <p-select v-model="form.productTypeId2" placeholder="请选择类别名称" showSearch @change="productTypeIdSelectChange2" >
                <p-select-option
                        v-for="(item,index) in productionTypeList"
                        :key="index"
                        :value="item.id+'-'+item.mtypename"
                >{{item.mtypename}}</p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col :span="12" >
            <p-form-model-item label="检验类型" prop="inspectType">
              <p-select v-model="form.inspectType" placeholder="请选择检验类型" @change="inspectTypeChange">
                <p-select-option
                        v-for="(item,index) in inspectTypeList"
                        :key="index"
                        :value="parseInt(item.value)"
                >{{item.title}}</p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col :span="12" >
            <p-form-model-item label="状态" prop="status">
              <p-radio-group v-model="form.status">
                <p-radio :value="1">
                  生效
                </p-radio>
                <p-radio :value="2">
                  失效
                </p-radio>
              </p-radio-group>
            </p-form-model-item>
          </p-col>

        </p-row>


        <p-divider orientation="left">
          检验规则
        </p-divider>


        <p-row :gutter="24"  >
          <p-form-model-item label="检验属性" prop="inspectAttribute">
            <p-radio-group v-model="form.inspectAttribute">
              <p-radio
                      v-for="(item,index) in inspectAttributeList"
                      :key="index"
                      :value="parseInt(item.value)"
              >
                {{item.title}}
              </p-radio>
            </p-radio-group>
          </p-form-model-item>


          <p-form-model-item label="加严系数" prop="tightCoefficient" v-if="form.inspectAttribute==1">
            <p-input v-model="form.tightCoefficient" @change="tightCoefficientChange" type="number" style="width:150px"></p-input>
          </p-form-model-item>

          <p-form-model-item label="是否动态调整" prop="isDynamicRegulation">
            <!--<p-radio-group v-model="form.isDynamicRegulation">
              <p-radio :value="1">
                是
              </p-radio>
              <p-radio :value="2">
                否
              </p-radio>
            </p-radio-group>-->

            <p-switch checked-children="是" un-checked-children="否" v-model="form.isDynamicRegulation" />
          </p-form-model-item>

          <p-form-model-item label="动态调整规则" prop="dynamicAdjustment">
            <p-input-group compact>
              <p-input addon-before="正常（N1）:" v-model="form.normalN1"  type="number" style="width:220px;margin-right: 10px" @change="numberChange4" :disabled="!form.isDynamicRegulation"></p-input>
              <p-input addon-before="直通（N2）:" v-model="form.passThroughN2"  type="number" style="width:220px"  @change="numberChange5" :disabled="!form.isDynamicRegulation"></p-input>
            </p-input-group>
          </p-form-model-item>

          <p-form-model-item label="是否需要供应商出厂报告" prop="isNeedCustoutrc" v-if="form.inspectType==5">
            <p-switch checked-children="是" un-checked-children="否" v-model="form.isNeedCustoutrc" />
          </p-form-model-item>

          <p-form-model-item label="抽样方式" prop="simplingMethod" >
            <p-radio-group v-model="form.simplingMethod" @change="simplingMethodSelectChange">
              <p-radio
                      v-for="(item,index) in simplingMethodList"
                      :key="index"
                      :value="parseInt(item.value)"
              >
                {{item.title}}
              </p-radio>
            </p-radio-group>
          </p-form-model-item>

          <p-form-model-item label="正常抽样数量" prop="normalSimplingQty" v-if="form.simplingMethod==1">
            <p-input-group compact >
              <p-select v-model="form.normalSimplingQtyType" @change="normalSimplingQtyTypeChange">
                <p-select-option :value="1">
                  数量
                </p-select-option>
                <p-select-option :value="2">
                  比例
                </p-select-option>
              </p-select>
              <p-input v-model="form.normalSimplingQty" v-if="form.normalSimplingQtyType==1" style="width:160px" type="number" @change="numberChange1"/>

              <p-input   v-model="form.normalSimplingQtyLeft" type="number" style="width:80px" v-if="form.normalSimplingQtyType==2" @change="numberChange2"/>
              <p-input
                      style=" width: 30px;  pointer-events: none;"
                      placeholder=":"
                      disabled
                      v-if="form.normalSimplingQtyType==2"
              />
              <p-input   v-model="form.normalSimplingQtyRight" type="number" style="width:80px;" v-if="form.normalSimplingQtyType==2" @change="numberChange3"/>
            </p-input-group>

          </p-form-model-item>

          <p-form-model-item label="AQL抽样标准" prop="aqlSimpleStandardName" v-if="form.simplingMethod==2">
            <p-select v-model="form.aqlSimpleStandardName" showSearch >
              <p-select-option
                      v-for="(item,index) in aqlNameList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>


          <p-form-model-item label="备注" prop="remark" >
            <p-input v-model="form.remark" />
          </p-form-model-item>


        </p-row>


      </p-form-model>
    </p-modal>







    <!-- 弹出窗 -->
    <Fx-compontens-modal
            @ok="modalFormOk"
            ref="modalCompon"
            :getList="queryInfo"
            :title="title"
            :dictOptions="dictOptions"
    ></Fx-compontens-modal>
  </p-card>
</template>

<script>
  import { JeecgListMixin } from "@/mixins/JeecgListMixin";
  import { api } from "@/api/manage";
  import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
  import { filterObj } from "@/utils/util";
  import MesQcInspectRuleBytypeModal from "./modules/MesQcInspectRuleBytypeModal";

  import Vue from "vue";
  import JDictSelectTag from "@/components/dict/JDictSelectTag.vue";
  import {
    initDictOptions,
    filterMultiDictText,
  } from "@/components/dict/JDictSelectUtil";
  import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
  import { postAction, getAction, deleteAction,putAction } from "@/api/manage";
  import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";

  //高级查询modal需要参数
  const superQueryFieldList = [
    {
      value: "productTypeCode",
      text: "类别编码",
      type: "string",
    },
    {
      value: "productType",
      text: "分类名称",
      type: "string",
    },
    {
      value: "inspectType",
      text: "检验类型",
      type: "select",
      dictCode: "inspect_type",
    },
    {
      value: "inspectAttribute",
      text: "检验属性",
      type: "select",
      dictCode: "inspect_attribute",
    },
    {
      value: "simplingMethod",
      text: "抽样方式",
      type: "select",
      dictCode: "rc_inspect_method",
    },
    {
      value: "normalSimplingQty",
      text: "正常抽样数量",
      type: "string",
    },
    {
      value: "aqlSimpleStandardName",
      text: "AQL抽样标准",
      type: "string",
    },
    {
      value: "tightCoefficient",
      text: "加严系数",
      type: "string",
    },
    {
      value: "isDynamicRegulation",
      text: "是否动态调整",
      type: "select",
      dictCode: "mes_is_use",
    },
    {
      value: "dynamicAdjustment",
      text: "动态调整规则",
      type: "string",
    },
    {
      value: "normalN1",
      text: "正常（N1）",
      type: "int",
    },
    {
      value: "passThroughN2",
      text: "直通（N2）",
      type: "int",
    },
    {
      value: "isNeedCustoutrc",
      text: "是否需要供应商出场记录",
      type: "select",
      dictCode: "mes_is_use",
    },
    {
      value: "status",
      text: "状态",
      type: "select",
      dictCode: "mes_status",
    },
    {
      value: "createBy",
      text: "创建人",
      type: "string",
    },
    {
      value: "createTime",
      text: "创建日期",
      type: "Date",
    },
    {
      value: "updateBy",
      text: "更新人",
      type: "string",
    },
    {
      value: "updateTime",
      text: "更新日期",
      type: "Date",
    },
    {
      value: "remark",
      text: "备注",
      type: "string",
    },
  ];

  export default {
    name: "MesQcInspectRuleBytypeList",
    mixins: [JeecgListMixin],
    components: {
      JSuperQuery,
      JDictSelectTag,
      FxCompontensModal,
      MesQcInspectRuleBytypeModal,
    },
    data() {
      return {
        fieldList: superQueryFieldList,
        superQueryFlag: false,
        superQueryParams: "",
        description: "检验规则维护（类别）管理页面",
        cgButtonLinkList: [],
        title: "", //存表名
        EnhanceJS: "",
        cgButtonList: [],
        groupTag: [],
        queryInfo: [],
        code: "",



        productionTypeList:[],
        productionTypeMap:[],
        inspectTypeList:[],
        inspectAttributeList:[],
        simplingMethodList:[],
        simplingMethodMap:[],

        aqlDataList:[],
        aqlDataMap:[],

        editP:{},

        pModalVisible:false,
        pTitle:'',
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
        currentState:1,

        form: {
          productTypeId:'',
          productTypeId2:'',
          productType:'',
          inspectType:'',
          status:1,
          inspectAttribute:3,
          tightCoefficient:'',
          isDynamicRegulation:true,
          normalN1:'',
          passThroughN2:'',
          isNeedCustoutrc:false,
          simplingMethod:1,
          normalSimplingQtyType:1,
          normalSimplingQty:'',
          normalSimplingQtyLeft:0,
          normalSimplingQtyRight:0,
          aqlSimpleStandardName:'',
          remark:'',
        },

        rules: {
          productTypeId: [{ required: true, message: '请选择物料类别', trigger: 'change' }],
          productTypeId2: [{ required: true, message: '请选择物料类别', trigger: 'change' }],
          productType: [{ required: false, message: '请输入类别名称', trigger: 'change' }],
          inspectType: [{ required: true, message: '请选择检验类型', trigger: 'change' }],
          status: [{ required: true, message: '请选择状态', trigger: 'change' }],
          inspectAttribute: [{ required: true, message: '请选择检验属性', trigger: 'change' }],
          isDynamicRegulation: [{ required: true, message: '请选择是否动态调整', trigger: 'change' }],
          normalN1: [{ required: true, message: '正常（N1）', trigger: 'change' }],
          passThroughN2: [{ required: true, message: '直通（N2）', trigger: 'change' }],
          simplingMethod: [{ required: true, message: '请选择抽样方式', trigger: 'change' }],

        },
        rowId:0,
        aqlNameList:[],

        // 表头
        columns: [],
        //列设置
        settingColumns: [],
        //列定义
        defColumns: [
          {
            title: "序号",
            dataIndex: "",
            key: "rowIndex",
            width: 60,
            fixed:'left',
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            },
          },
          {
            title: "类别编码",
            align: "center",
            width: 150,
            fixed:'left',
            dataIndex: "productTypeCode",
          },
          {
            title: "分类名称",
            align: "center",
            width: 150,
            fixed:'left',
            dataIndex: "productType",
          },
          {
            title: "检验类型",
            align: "center",
            dataIndex: "inspectType_dictText",
            scopedSlots: { customRender: "inspectType_dictText" },
          },
          {
            title: "是否需要供应商出厂记录",
            align: "center",
            width:150,
            dataIndex: "isNeedCustoutrc",
            customRender:(text)=>{
              if(!text){
                return "";
              }else{
                return text==1?'是':'否';
              }
            }
          },
          {
            title: "检验属性",
            align: "center",
            dataIndex: "inspectAttribute_dictText",
          },
          {
            title: "抽样方式",
            align: "center",
            dataIndex: "simplingMethod_dictText",
          },
          {
            title: "正常抽样数量",
            align: "center",
            dataIndex: "normalSimplingQty",
          },
          {
            title: "AQL抽样标准",
            align: "center",
            dataIndex: "aqlSimpleStandardName",
          },

          {
            title: "是否动态调整",
            align: "center",
            dataIndex: "isDynamicRegulation",
            customRender:(text)=>{
              if(!text){
                return "";
              }else{
                return text==1?'是':'否';
              }
            }
          },
          // {
          //   title: '动态调整规则',
          //   align: 'center',
          //   dataIndex: 'dynamicAdjustment',
          // },
          {
            title: "正常（N1）",
            align: "center",
            dataIndex: "normalN1",

          },
          {
            title: "直通（N2）",
            align: "center",
            dataIndex: "passThroughN2",

          },

          {
            title: "加严系数",
            align: "center",
            dataIndex: "tightCoefficient",
            scopedSlots: { customRender: "tightCoefficient" },
          },
          {
            title: "创建人工号",
            align: "center",
            dataIndex: "createCode",
          },
          {
            title: "创建人",
            align: "center",
            dataIndex: "createBy",
          },
          {
            title: "创建日期",
            align: "center",
            dataIndex: "createTime",
            customRender: function (text) {
              return !text ? "" : text.length > 20 ? text.substr(0, 20) : text;
            },
          },
          {
            title: "更新人工号",
            align: "center",
            dataIndex: "updateCode",
          },
          {
            title: "更新人",
            align: "center",
            dataIndex: "updateBy",
          },
          {
            title: "更新日期",
            align: "center",
            dataIndex: "updateTime",
            customRender: function (text) {
              return !text ? "" : text.length > 20 ? text.substr(0, 20) : text;
            },
          },

          {
            title: "备注",
            align: "center",
            width:230,
            dataIndex: "remark",
          },
          {
            title: "状态",
            align: "center",
            fixed:'right',
            dataIndex: "status_dictText",
            scopedSlots: { customRender: "status_dictText" },
          },
          {
            title: "操作",
            dataIndex: "action",
            width:130,
            fixed:'right',
            align: "center",
            scopedSlots: { customRender: "action" },
          },
        ],
        url: {
          list: "/mes-quality/mesQcInspectRuleBytype/list",
          delete: "/mes-quality/mesQcInspectRuleBytype/delete",
          deleteBatch: "/mes-quality/mesQcInspectRuleBytype/deleteBatch",
          exportXlsUrl: "/mes-quality/mesQcInspectRuleBytype/exportXls",
          importExcelUrl: "/mes-quality/mesQcInspectRuleBytype/importExcel",
          getColumns: "/mes-quality/online/cgform/api/getColumns/",
          buttonAction: "/mes-quality/online/cgform/api/doButton",
        },
        dictOptions: {},
      };
    },
    computed: {
      importExcelUrl: function () {
        return `${api.test}${this.url.importExcelUrl}`;
      },
      getWidth: function () {
        if (this.defColumns.length > 14) {
          return { width: "500px" };
        }
      },
      tableScroll: function () {
        if (this.columns.length > 13) {
          return { x: this.columns.length * 150 - 660 };
        }
      },
    },
    created() {
      this.initAqlNameList();
      this.initSimplingMethodList();
      this.initInspectAttributeList();
      this.initInspectTypeList();
      this.initProductionTypeList();
      this.initButtonList();
      this.setdefColumns();
      this.initColumns();
    },

    methods: {
      clickThenSelect(record) {
        return {
          on: {
            click: () => {
              if(record.id){
                this.rowId = record.id;
                //this.onSelectChange(record.id.split(","), [record]);
              }

            },
          },
        };
      },
      setRowClassName(record){
        return record.id === this.rowId ? 'clickRowStyl' : '';
      },
      setdefColumns() {
        if (this.defColumns.length > 13) {
          let arrLength = this.columns.length - 1


        }
      },
//封装listToMap
      listToMap(list,name){
        let map = {};
        for(let i in list){
          map[list[i][name]] = list[i];
        }
        return map;
      },

      deleteBtn(id){
        deleteAction('/mes-quality/mesQcInspectRuleBytype/delete/'+id).then(res=>{
          if(res.success){
            this.$message.success("删除成功!");
            this.loadData();
          }else{
            this.$message.warning("删除失败!");
          }
        })
      },

      initAqlNameList(){
        getAction('/mes-quality/mesQcAqlSampleStandard/queryAqlName').then(res=>{
          if(res.success){
            this.aqlNameList = res.data;
          }
        })
      },

      initAqlDataList(){
        getAction('/mes-quality/mesQcAqlSampleStandard/selectAll').then(res=>{
          if(res.success){
            this.aqlDataList = res.data;
            this.aqlDataMap = this.listToMap(this.aqlDataList,'id');
          }
        })
      },

      initProductionTypeList(){
        getAction('/basic-business/auto/baCptype/childList').then(res=>{
          if(res.success){
            this.productionTypeList = res.data;
            this.productionTypeMap = this.listToMap(this.productionTypeList,'id');
          }
        })
      },

      initInspectTypeList(){
        getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'inspect_type'}).then(res=>{
          if(res.success){
            this.inspectTypeList = res.data;
          }
        })
      },

      initInspectAttributeList(){
        getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'inspect_attribute '}).then(res=>{
          if(res.success){
            this.inspectAttributeList = res.data;
          }
        })
      },

      initSimplingMethodList(){
        getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'rc_inspect_method '}).then(res=>{
          if(res.success){
            this.simplingMethodList = res.data;
            this.simplingMethodMap = this.listToMap(this.simplingMethodList,'id');
          }
        })
      },



      openAddBtn(){
        if(this.currentState =2){
          this.formDataInit();
        }
        this.pModalVisible = true;
        this.currentState =1;
        this.pTitle = '新增';
      },

      openEditBtn(record){
        this.pModalVisible = true;
        this.currentState =2;
        this.pTitle = '编辑';

        this.editP = record;
        let data = record;

        this.form={
          inspectType:data.inspectType,
          status:data.status,
          inspectAttribute:data.inspectAttribute,
          tightCoefficient:data.tightCoefficient,
          isDynamicRegulation:data.isDynamicRegulation==1?true:false,
          normalN1:data.normalN1,
          passThroughN2:data.passThroughN2,
          isNeedCustoutrc:data.isNeedCustoutrc==1?true:false,
          simplingMethod:data.simplingMethod,
          aqlSimpleStandardName:data.aqlSimpleStandardName,
          remark:data.remark
        }

        if(this.productionTypeMap[data.productTypeId]){
          let item = this.productionTypeMap[data.productTypeId];
          Vue.set(this.form,'productTypeId',item.id+'-'+item.mtypeno);
          Vue.set(this.form,'productType',item.mtypename);
          Vue.set(this.form,'productTypeId2',item.id+'-'+item.mtypename);
        }

        if(data.simplingMethod==1){
          let normalSimplingQty= data.normalSimplingQty;
          if(normalSimplingQty.split(':').length>1){
            Vue.set(this.form,'normalSimplingQtyType',2);
            Vue.set(this.form,'normalSimplingQty',0);
            Vue.set(this.form,'normalSimplingQtyLeft',normalSimplingQty.split(':')[0]);
            Vue.set(this.form,'normalSimplingQtyRight',normalSimplingQty.split(':')[1]);
          }else{
            Vue.set(this.form,'normalSimplingQtyType',1);
            Vue.set(this.form,'normalSimplingQty',parseInt(data.normalSimplingQty));
          }
        }


      },

      numberCheck(val){
        // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除，

        if(val === "" || val ==null){
          return false;
        }
        if(!isNaN(val)){
          //对于空数组和只有一个数值成员的数组或全是数字组成的字符串，isNaN返回false，例如：'123'、[]、[2]、['123'],isNaN返回false,
          //所以如果不需要val包含这些特殊情况，则这个判断改写为if(!isNaN(val) && typeof val === 'number' )

          if(val<=0){
            return false;
          }else{
            return true;
          }
        }

        else{
          return false;
        }
      },


      pModalOk(){
        let data  =this.form;
        let flag = true;

        if(data.simplingMethod==2){
          if(data.aqlSimpleStandardName==''){
            flag = false;
            this.$message.error("请选择AQL抽样标准");
          }
        }
        if(data.inspectAttribute==1){
          if(!this.numberCheck(data.tightCoefficient)){

            flag = false;
            this.$message.error("'加严系数' 值错误");
          }else{
            if(data.tightCoefficient<=1){
              flag = false;
              this.$message.error("'加严系数' 值错误(必须大于1)");
            }
          }
        }

        if(data.isDynamicRegulation){
          if(!this.numberCheck(data.normalN1)){
            flag = false;
            this.$message.error("'动态调整规则-正常（N1）' 值错误");
          }
          if(!this.numberCheck(data.passThroughN2)){
            flag = false;
            this.$message.error("'动态调整直通（N2）' 值错误");
          }
        }

        if(data.simplingMethod==1){
          if(data.normalSimplingQtyType==1){
            if(!this.numberCheck(data.normalSimplingQty)){
              flag = false;
              this.$message.error("'正常抽样数量' 值错误");
            }
          }else{
            if(!this.numberCheck(data.normalSimplingQtyLeft)||!this.numberCheck(data.normalSimplingQtyRight)){
              flag = false;
              this.$message.error("'正常抽样数量' 值错误");
            }
          }

        }


        if(flag){
          this.$refs.ruleForm.validate(valid => {
            if (valid) {
              if(this.currentState==1){
                this.pAddOperation();
              }else if(this.currentState==2){
                this.pEditOperation();
              }
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        }
      },

      dataFormReset(){
        let data = this.form;
        console.log(data.remark)
        let result={

          inspectType:data.inspectType,
          status:data.status,
          inspectAttribute:data.inspectAttribute,
          tightCoefficient:data.tightCoefficient,
          isDynamicRegulation:data.isDynamicRegulation?1:2,
          normalN1:data.normalN1,
          passThroughN2:data.passThroughN2,
          isNeedCustoutrc:data.isNeedCustoutrc?1:2,
          simplingMethod:data.simplingMethod,
          aqlSimpleStandardName:data.aqlSimpleStandardName,
          remark:data.remark
        }

        let productTypeId = data.productTypeId;
        let id = productTypeId.split('-')[0];

        if(this.productionTypeMap[id]){
          result.productTypeId = parseInt(id);
          result.productTypeCode = this.productionTypeMap[id].mtypeno;
          result.productType = this.productionTypeMap[id].mtypename;
        }

        if(result.simplingMethod==1){
          if(data.normalSimplingQtyType==1){
            result.normalSimplingQty = data.normalSimplingQty+'';
          }else{
            result.normalSimplingQty = data.normalSimplingQtyLeft+':'+data.normalSimplingQtyRight;
          }
        }else{
          result.normalSimplingQty = '';
        }


        return result;

      },

      pAddOperation(){
        let data = this.dataFormReset();
        postAction('/mes-quality/mesQcInspectRuleBytype/add',data).then(res=>{
          if(res.success){
            this.pModalVisible = false;
            this.$message.success('新增成功！');
            this.loadData();
            this.formDataInit();
          }else{
            this.$message.warning(res.msg);
          }
        })
      },

      pEditOperation(){
        let data = this.dataFormReset();
        let result = this.editP;

        result.productTypeId= data.productTypeId;
        result.productTypeCode=data.productTypeCode;
        result.productType = data.productType;
        result.inspectType=data.inspectType;
        result.status=data.status;
        result.inspectAttribute=data.inspectAttribute;
        result.tightCoefficient=data.tightCoefficient;
        result.isDynamicRegulation=data.isDynamicRegulation;
        result.normalN1=data.normalN1;
        result.passThroughN2=data.passThroughN2;
        result.isNeedCustoutrc=data.isNeedCustoutrc;
        result.simplingMethod=data.simplingMethod;
        result.normalSimplingQty = data.normalSimplingQty
        result.aqlSimpleStandardName = data.aqlSimpleStandardName
        result.remark = data.remark;


        putAction('/mes-quality/mesQcInspectRuleBytype/edit',result).then(res=>{
          if(res.success){
            this.pModalVisible = false;
            this.$message.success('编辑成功！');
            this.loadData();
            this.formDataInit();
          }else{
            this.$message.warning(res.msg);
            this.loadData();
          }
        })
      },


      formDataInit(){
        this.form={

          productTypeId:'',
          productType:'',
          inspectType:'',
          status:1,
          inspectAttribute:3,
          tightCoefficient:'',
          isDynamicRegulation:true,
          normalN1:'',
          passThroughN2:'',
          isNeedCustoutrc:false,
          simplingMethod:1,
          normalSimplingQtyType:1,
          normalSimplingQty:'',
          normalSimplingQtyLeft:0,
          normalSimplingQtyRight:0,
          aqlSimpleStandardName:'',
          remark:'',
        }
      },

      simplingMethodSelectChange(){
        this.form.aqlSimpleStandardName='';
        this.form.normalSimplingQty='';

      },

      productTypeIdSelectChange(){
        let productTypeId = this.form.productTypeId;
        if(productTypeId){
          let id = parseInt(productTypeId.split('-')[0]);
          if(this.productionTypeMap[id]){

            this.form.productTypeId2 = id+'-'+this.productionTypeMap[id].mtypename;
          }
        }

      },

      productTypeIdSelectChange2(){
        let productTypeId = this.form.productTypeId2;
        if(productTypeId){
          let id = parseInt(productTypeId.split('-')[0]);
          if(this.productionTypeMap[id]){

            this.form.productTypeId = id+'-'+this.productionTypeMap[id].mtypeno;
          }
        }

      },

      sqlSimpleSelectChange(){
        let aqlSimpleId = this.form.aqlSimpleId;
        if(aqlSimpleId){
          let id = parseInt(aqlSimpleId.split('-')[0]);
          if(this.aqlDataMap[id]){
            this.form.normalSimplingQty = this.aqlDataMap[id].sampleQty;
          }
        }

      },


      inspectTypeChange(){
        if(this.form.inspectType!=5){
          this.form.isNeedCustoutrc = false;
        }
      },

      normalSimplingQtyTypeChange(){
        if(this.form.normalSimplingQtyType==1){
          this.form.normalSimplingQty= 0;
        }else{
          this.form.normalSimplingQtyLeft = 0;
          this.form.normalSimplingQtyRight = 0;
        }
      },


      numberChange1(){
        /*if(this.form.normalSimplingQty==''){
          this.form.normalSimplingQty = 0;
        }*/
      },
      numberChange2(){
        if(this.form.normalSimplingQtyLeft==''){
          this.form.normalSimplingQtyLeft = 0;
        }
      },
      numberChange3(){
        if(this.form.normalSimplingQtyRight==''){
          this.form.normalSimplingQtyRight = 0;
        }
      },
      numberChange4(){
        /* if(this.form.normalN1==''){
           this.form.normalN1 = 0;
         }*/
      },
      numberChange5(){
        /*if(this.form.passThroughN2==''){
          this.form.passThroughN2 = 0;
        }*/
      },





      tightCoefficientChange(){
        /*if(this.form.tightCoefficient==''){
          this.form.tightCoefficient=2;
        }*/
      },


      //确定按钮
      handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        this.searchText = selectedKeys[0];
        this.searchedColumn = dataIndex;
      },
      //取消按钮
      handleReset(clearFilters) {
        clearFilters();
        this.searchText = "";
      },
      //确定时间
      handleSearchDate(selectedKeys, confirm, dataIndex) {
        confirm();
        this.searchText = selectedKeys[0];
        this.searchedColumn = dataIndex;
        this.searchQuery();
      },
      // 清除时间
      handleResetDate(clearFilters, begin, end) {
        if (this.queryParam[begin] || this.queryParam[end]) {
          this.queryParam[begin] = "";
          this.queryParam[end] = "";
          clearFilters();
          this.searchText = "";
          this.searchQuery();
        } else {
          clearFilters();
          this.searchText = "";
        }
      },
      getKey() {
        const dataItem = [];
        setTimeout(() => {
          this.columns.forEach((item) => {
            dataItem.push({ text: item.title, value: item.dataIndex });
          });
        }, 100);
        return dataItem;
      },
      //
      getControl(dic) {
        const dataItem = [];
        initDictOptions(dic).then((res) => {
          res.data.forEach((item) => {
            dataItem.push({ text: item.text, value: item.value });
          });
        });
        return dataItem;
      },
      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name + ":colsettings";
        let colSettings = Vue.ls.get(key);
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = [];
          this.defColumns.forEach(function (item, i, array) {
            allSettingColumns.push(item.dataIndex);
          });
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        } else {
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter((item) => {
            if (item.key == "rowIndex" || item.dataIndex == "action") {
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          });
          this.columns = cols;
        }
      },
      //列设置更改事件
      onColSettingsChange(checkedValues) {
        var key = this.$route.name + ":colsettings";
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      },

      //高级查询方法
      handleSuperQuery(arg) {
        if (!arg) {
          this.superQueryParams = "";
          this.superQueryFlag = false;
        } else {
          this.superQueryFlag = true;
          this.superQueryParams = JSON.stringify(arg);
        }
        this.loadData();
      },
      // 获取查询条件
      getQueryParams() {
        let sqp = {};
        if (this.superQueryParams) {
          sqp["superQueryParams"] = encodeURI(this.superQueryParams);
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.limit = this.ipagination.pageSize;
        return filterObj(param);
      },
      initDictConfig() {},

      // 弹出窗组件
      showDemoModal() {
        this.$refs.modalCompon.modalShow();
      },
      // 点击btn获取数据
      btnGetData(tableName, title) {
        getAction(`${this.url.getColumns}`, {
          tableName: tableName,
        }).then((res) => {
          if (res.code == 0) {
            this.queryInfo = res.data.columns;
            this.title = title;
            this.dictOptions = res.data.dictOptions;
            this.showDemoModal();
          } else {
            this.$message.warning(res.msg);
          }
        });
      },

      //筛选分组
      getGroupTag(arrList) {
        let arr = [];
        var map = {},
                dest = [];
        arrList.forEach((item, index) => {
          if (item.groupTag) {
            arr.push(item);
          }
        });
        for (var i = 0; i < arr.length; i++) {
          var ai = arr[i];
          if (!map[ai.groupTag]) {
            dest.push({
              groupTag: ai.groupTag,
              name: ai.groupName,
              data: [ai],
            });
            map[ai.groupTag] = ai;
          } else {
            for (var j = 0; j < dest.length; j++) {
              var dj = dest[j];
              if (dj.groupTag == ai.groupTag) {
                dj.data.push(ai);
                break;
              }
            }
          }
        }
        this.groupTag = dest;
        console.log(dest);
      },
      showLinkButton(item, record) {
        let btn = new ButtonExpHandler(item.exp, record);
        return btn.show;
      },
      initButtonList() {
        getAction(`${this.url.getColumns}8ac49ec7733bce4801733d2129f6001f`).then(
                (res) => {
                  console.log("--获取自定义按钮->>", res);
                  if (res.success) {
                    this.code = res.data.code;
                    this.initCgButtonList(res.data.cgButtonList);
                    this.initCgEnhanceJs(res.data.enhanceJs);
                    this.getGroupTag(res.data.cgButtonList);
                  } else {
                    this.$message.warning(res.msg);
                  }
                }
        );
      },
      initCgEnhanceJs(enhanceJs) {
        //console.log("--onlineList-js增强",enhanceJs)
        if (enhanceJs) {
          let Obj = eval("(" + enhanceJs + ")");
          this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
          this.cgButtonJsHandler("created");
        } else {
          this.EnhanceJS = "";
        }
      },
      initCgButtonList(btnList) {
        let linkArr = [];
        let buttonArr = [];
        if (btnList && btnList.length > 0) {
          for (let i = 0; i < btnList.length; i++) {
            let temp = btnList[i];
            if (temp.buttonStyle == "button") {
              buttonArr.push(temp);
            } else if (temp.buttonStyle == "link") {
              linkArr.push(temp);
            }
          }
        }
        this.cgButtonLinkList = [...linkArr];
        this.cgButtonList = [...buttonArr];
        console.log("链接增强", this.cgButtonLinkList);
      },
      cgButtonJsHandler(buttonCode) {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this);
        }
      },
      cgButtonActionHandler(buttonCode) {
        //处理自定义button的 需要配置该button自定义sql
        if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
          this.$message.warning("请先选中一条记录");
          return false;
        }
        if (this.selectedRowKeys.length > 1) {
          this.$message.warning("请只选中一条记录");
          return false;
        }
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: this.selectedRowKeys[0],
        };
        console.log("自定义按钮请求后台参数：", params);
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        var params = this.getQueryParams() // 查询条件
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.data.records
            this.ipagination.total = res.data.total
          }
          if (res.code === 510) {
            this.$message.warning(res.msg)
          }
        }).then(res=>{
          this.loading = false
        })
      },
      cgButtonLinkHandler(record, buttonCode, optType) {
        if (optType == "js") {
          if (this.EnhanceJS[buttonCode]) {
            this.EnhanceJS[buttonCode](this, record);
          }
        } else if (optType == "action") {
          let params = {
            formId: this.code,
            buttonCode: buttonCode,
            dataId: record.id,
          };
          console.log("自定义按钮link请求后台参数：", params);
          postAction(this.url.buttonAction, params).then((res) => {
            if (res.success) {
              this.loadData();
              this.$message.success("处理完成!");
            } else {
              this.$message.warning("处理失败!");
            }
          });
        }
      },
    },
  };
</script>
<style scoped>
  @import "~@assets/less/common.less";
  /deep/.clickRowStyl td{
    background:#00b4ed !important;
  }

  /deep/.ant-table-tbody.clickRowStyl:hover>td {
    background-color:#00b4ed
  }
</style>